package com.clock.album;

import com.clock.album.slice.ShowImageFileAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class ShowImageFileAbility extends Ability {
    private TableLayout tableLayout;
    private ArrayList<Integer> datalist;
    private boolean[] mListBool;
    private ArrayList<Integer> intentList=new ArrayList<>();
    private Text sure;
    private ArrayList<PixelMap> pixelMaps=new ArrayList<>();
    private DataAbilityHelper helper;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_show_image_file);
        tableLayout= (TableLayout) findComponentById(ResourceTable.Id_table_layout);
        findComponentById(ResourceTable.Id_back).setClickedListener(component ->
                onBackPressed());
        sure= (Text) findComponentById(ResourceTable.Id_sure);
        sure.setClickedListener(component -> onBackPressedSure());
        String title=getIntent().getStringParam("title");
        ((Text)findComponentById(ResourceTable.Id_title)).setText(title.isEmpty()?"相册":title);
        datalist=getIntent().getIntegerArrayListParam("datalist");
        sure.setText("(0/"+datalist.size()+")确定");
        helper = DataAbilityHelper.creator(this);
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<datalist.size();i++){
                    PixelMap pixelMap = null;
                    ImageSource imageSource = null;
                    String id=""+datalist.get(i);
                    Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, id);
                    FileDescriptor fd = null;
                    try {
                        fd = helper.openFile(uri, "r");
                    } catch (DataAbilityRemoteException e) {
                        e.printStackTrace();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    try {
                        imageSource = ImageSource.create(fd, null);
                        // 设置图片参数
                        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                        // 缩放
                        decodingOptions.desiredSize = new Size(250, 250);
                        // 剪裁
//                        decodingOptions.desiredRegion = new Rect(0, 0, 250, 250);
                        decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
                        pixelMap = imageSource.createPixelmap(decodingOptions);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (imageSource != null) {
                            imageSource.release();
                        }
                    }
                    pixelMaps.add(pixelMap);
                }
                initView();
            }
        });

    }
    private void initView(){
        if(datalist!=null&&datalist.size()>0){
            mListBool=new boolean[datalist.size()];
            for(int i=0;i<datalist.size();i++){
                int finalI = i;
//                PixelMap pixelMap = null;
//                ImageSource imageSource = null;
//                String id=""+datalist.get(i);
                Component component= LayoutScatter.getInstance(this).parse(ResourceTable.Layout_listfile_list_image_item,null,false);
                Image image = (Image) component.findComponentById(ResourceTable.Id_image);
//                image.setWidth(250);
//                image.setHeight(250);
//                image.setMarginsLeftAndRight(5, 5);
//                image.setMarginsTopAndBottom(5, 5);
                image.setScaleMode(Image.ScaleMode.STRETCH);
//                Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, id);
//                FileDescriptor fd = null;
//                try {
//                    fd = helper.openFile(uri, "r");
//                } catch (DataAbilityRemoteException e) {
//                    e.printStackTrace();
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
//                try {
//                    imageSource = ImageSource.create(fd, null);
//                    pixelMap = imageSource.createPixelmap(null);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally {
//                    if (imageSource != null) {
//                        imageSource.release();
//                    }
//                }
                image.setPixelMap(pixelMaps.get(i));
                //image.setPixelMap(ResourceTable.Media_img_default);
                Image checkbox= (Image) component.findComponentById(ResourceTable.Id_check_box_iv);
                checkbox.setPixelMap(ResourceTable.Media_image_unselected);
                mListBool[i]=false;
                checkbox.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        mListBool[finalI]=!mListBool[finalI];
                        if(mListBool[finalI]){
                            checkbox.setPixelMap(ResourceTable.Media_image_selected);
                        }else {
                            checkbox.setPixelMap(ResourceTable.Media_image_unselected);
                        }
                        getIsCheckVue();
                    }
                });
                image.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        Intent intent1 = new Intent();
                        Operation operation = new Intent.OperationBuilder()
                                .withBundleName("com.clock.album")
                                .withAbilityName("com.clock.album.ImageAbility")
                                .build();
                        intent1.setOperation(operation);
                        intent1.setParam("index", finalI);
                        intent1.setIntegerArrayListParam("mList",datalist);
                        intent1.setParam("mListBool",mListBool);
                        startAbilityForResult(intent1,10010);
                    }
                });
                tableLayout.addComponent(component);
            }
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        switch (requestCode){
            case 10010:
                if(resultData!=null){
                    mListBool=resultData.getBooleanArrayParam("mListBool");
                    setCheckBoxChecked();
                    getIsCheckVue();
                }
                break;
        }
    }

    public void onBackPressedSure() {
        initIntentList();
        if(intentList.isEmpty()){
            new ToastDialog(this).setContentText("请至少选择一张确认").show();
            return;
        }
        Intent intent=new Intent();
        intent.setIntegerArrayListParam("datalist",intentList);
        setResult(1,intent);
        terminateAbility();
    }
    private void setCheckBoxChecked(){
        for(int i=0;i<tableLayout.getChildCount();i++){
            Component component=tableLayout.getComponentAt(i);
            Image checkbox= (Image) component.findComponentById(ResourceTable.Id_check_box_iv);
            if(mListBool[i]){
                checkbox.setPixelMap(ResourceTable.Media_image_selected);
            }else {
                checkbox.setPixelMap(ResourceTable.Media_image_unselected);
            }
        }
    }
    private void initIntentList(){
        intentList.clear();
        for (int i=0;i<datalist.size();i++){
            if(mListBool[i]){
                intentList.add(datalist.get(i));
            }
        }
    }
    private void getIsCheckVue(){
        int value=0;
        for (int i=0;i<mListBool.length;i++){
            if(mListBool[i]){
                value++;
            }
        }
        int finalValue = value;
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                sure.setText("("+ finalValue +"/"+datalist.size()+")确定");
            }
        });
    }

}
